import 'dart:async';
import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:fate_blind_box/chat_view/chat_net_image.dart';
import 'package:fate_blind_box/config/app_style.dart';
import 'package:fate_blind_box/network/Api.dart';
import 'package:fate_blind_box/theme/theme_color.dart';
import 'package:fate_blind_box/ui/matcher/matcher_detail.dart';
import 'package:fate_blind_box/ui/matcher/matcher_list.dart';
import 'package:fate_blind_box/ui/moment/list.dart';
import 'package:fate_blind_box/utils/default/common_config.dart';
import 'package:fate_blind_box/utils/loading.dart';
import 'package:fate_blind_box/utils/provider.dart';
import 'package:fate_blind_box/widget/icon_text.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../utils/map/map_common_config.dart';
import '../../utils/page.dart';
import '../../utils/snack_bar.dart';
import '../Home/activity/home_act_tab_page.dart';
import '../Home/fate/fate_list.dart';
import '../Home/map/near_by_map_view/near_by_map_page.dart';
import '../Home/fate/fate_line.dart';
import '../Home/qsy/qsy_list_page.dart';
import '../Home/qsy/zxyp_list_page.dart';
import 'home_main_controller.dart';
import 'package:get/get.dart';

class HomeUi extends StatefulWidget {
  const HomeUi({Key? key}) : super(key: key);

  @override
  State<HomeUi> createState() => _HomeUiState();
}

class _HomeUiState extends State<HomeUi> {
  late Size _size;
  late double _screenWidth, _screenHeight;
  int realSex = -1;
  bool isShow = false;

  HomeMainController homeMainController = Get.put(HomeMainController());
  late StreamSubscription<Map<String, Object>> _locationListener;
  double imgHeight = 36;
  TextStyle wrapFontStyle =
      TextStyle(fontSize: 12, color: ThemeColor.black2E363DColor);

  final AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  @override
  void initState() {
    super.initState();
    _getUserInfo();
    _getList();
    homeMainController.markList = [];
    homeMainController.getMapShopList(0.000000, 0.000000);
    getCurrentLocation();
    if (CommonConfig.isHuaWeiPermission) {
      isOpenLocationPermission().then((value) {
        homeMainController.isShowPermission = value;
        homeMainController.update([homeMainController.showPermissionViewId]);
      });
    }
  }

  _getUserInfo() {
    loading(() async {
      final res = await Api.getInstance().getMemberInfo(Provider.memberId);
      if (res['code'] == 0) {
        final data = res['data'];
        realSex = data['realSex'];
      } else {
        ThemeSnackBar.show(context, res['msg']);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: '#F8F8F8'.stringToColor,
      body: Stack(
        children: [
          buildContent(),
          Positioned(
            child: GetBuilder(
                id: homeMainController.showPermissionViewId,
                builder: (HomeMainController mainController) {
                  return Visibility(
                    visible: mainController.isShowPermission,
                    child: GestureDetector(
                      onTap: () {
                        mainController.isShowPermission = false;
                        mainController
                            .update([homeMainController.showPermissionViewId]);
                      },
                      child: Container(
                        width: 1.sw,
                        height: 1.sh,
                        color: const Color.fromRGBO(0, 0, 0, 0.2),
                        child: Column(
                          children: [
                            Container(
                              padding: EdgeInsets.only(
                                  left: 30, top: ScreenUtil().statusBarHeight),
                              width: 1.sw,
                              height: 90,
                              color: Colors.white,
                              child: const Text(
                                '位置权限说明\n获取您当前的位置，为您匹配附近的红娘',
                                style: TextStyle(fontSize: 16),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                }),
          ),
        ],
      ),
    );
  }

  Future<bool> isOpenLocationPermission() async {
    var status = await Permission.location.status;
    if (status.isGranted) {
      return false;
    }
    return true;
  }

  /// 创建标题栏
  Container buildTitleBar() {
    return Container(
      height: 56,
      color: Colors.white,
      child: Stack(
        children: [
          Center(
            child: Text(
              "首页",
              style: TextStyle(color: ThemeColor.textColor, fontSize: 16),
            ),
          ),
          Positioned(
            right: 12,
            height: 28,
            width: 74,
            top: 14,
            child: GestureDetector(
              onTap: () {
                Navigator.of(context).push(
                    MaterialPageRoute(builder: (ctx) => const CycleListUi()));
              },
              child: Container(
                  decoration: ShapeDecoration(
                      shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(14)),
                      color: const Color(0xFFF7F7F7)),
                  child: Row(
                    // crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        "images/ic_hqz.png",
                        width: 18,
                        height: 18,
                      ),
                      Text(
                        " 圈子 ",
                        style: TextStyle(
                            color: ThemeColor.textColor, fontSize: 14),
                      ),
                      Icon(
                        Icons.arrow_forward_ios,
                        color: ThemeColor.textColor,
                        size: 12,
                      )
                    ],
                  )),
            ),
          )
        ],
      ),
    );
  }

  /// 创建滚动区域
  NestedScrollView buildContent() {
    return NestedScrollView(
      headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
        return [
          buildBanner(),
          buildMenus(),
          buildListTitle('热心红娘', '查看更多'),
        ];
      },
      body: buildGridView(),
    );
  }

  /// 轮播图
  Widget buildBanner() {
    List<String> imgList = [
      "images/ic_oryj.png",
      "images/ic_jzpp.png",
    ];
    return SliverToBoxAdapter(
        child: Container(
      padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight + 22),
      decoration: BoxDecoration(
        gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomLeft,
            colors: [
              const Color.fromRGBO(239, 233, 255, 1),
              ThemeColor.grayF8F8F8Color,
            ]),
      ),
      child: AspectRatio(
        //设置图片的展示比例之后，可以不设置外层的宽度，或者设置成infinity
        aspectRatio: 350 / 150,
        child: Swiper(
          itemCount: imgList.length,
          itemBuilder: (BuildContext context, int index) {
            return Container(
                margin: const EdgeInsets.symmetric(vertical: 5, horizontal: 12),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(5),
                  child: Image.asset(
                    imgList[index],
                    fit: BoxFit.fill,
                  ),
                ));
          },
          //分页指示器
          pagination: const SwiperPagination(builder: SwiperPagination.rect),
          //页面上的左右箭头
          control: null,
          //自动轮播
          autoplay: true,
          loop: true,
        ),
      ),
    ));
  }

  /// 菜单
  Widget buildMenus() {
    final _menuWidth = (ScreenUtil().screenWidth - 100) / 4;
    return SliverToBoxAdapter(
      child: Container(
        decoration: ShapeDecoration(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(5),
          ),
          color: Colors.white,
        ),
        margin: const EdgeInsets.only(top: 15, left: 14, right: 14),
        child: Column(
          children: [
            const SizedBox(
              height: 15,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                GestureDetector(
                    onTap: () {
                      // 诚信约会
                      // Navigator.of(context).push(MaterialPageRoute(builder: (builder) => const BlindTrustUi()));
                      // 圈子
                      Navigate.toPage(const CycleListUi());
                    },
                    child: Column(
                      children: [
                        Image.asset(
                          "images/ic_mequanz.png",
                          height: imgHeight,
                          fit: BoxFit.fitHeight,
                        ),
                        const SizedBox(height: 3),
                        Text(
                          '我的圈子',
                          style: wrapFontStyle,
                        ),
                      ],
                    )),
                GestureDetector(
                    onTap: () {
                      Get.to(const HomeActTabPage());
                    },
                    child: Column(
                      children: [
                        Image.asset(
                          "images/ic_xiangqinhd.png",
                          height: imgHeight,
                          fit: BoxFit.fitHeight,
                        ),
                        const SizedBox(height: 3),
                        Text(
                          '相亲活动',
                          style: wrapFontStyle,
                        ),
                      ],
                    )),
                GestureDetector(
                    onTap: () {
                      jumpNearByView();
                    },
                    child: Column(
                      children: [
                        Image.asset(
                          "images/ic_chihewl.png",
                          height: imgHeight,
                          fit: BoxFit.fitHeight,
                        ),
                        const SizedBox(height: 3),
                        Text(
                          '吃喝玩乐',
                          style: wrapFontStyle,
                        ),
                      ],
                    )),
                GestureDetector(
                    onTap: () {
                      // 单身驿站
                      jumpNearByView();
                    },
                    child: Column(
                      children: [
                        Image.asset(
                          "images/ic_danshenyz.png",
                          height: 36,
                          fit: BoxFit.fitHeight,
                        ),
                        const SizedBox(height: 3),
                        Text(
                          '单身驿站',
                          style: wrapFontStyle,
                        ),
                      ],
                    )),
              ],
            ),
            const SizedBox(
              height: 10,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                GestureDetector(
                    onTap: () {
                      Navigate.toPage(const QSYListPage());
                    },
                    child: Column(
                      children: [
                        Image.asset(
                          "images/ic_qsy.png",
                          height: imgHeight,
                          fit: BoxFit.fitHeight,
                        ),
                        const SizedBox(height: 3),
                        Text(
                          '轻松游',
                          style: wrapFontStyle,
                        ),
                      ],
                    )),
                GestureDetector(
                    onTap: () {
                      Get.to(const ZXYPListPage());
                    },
                    child: Column(
                      children: [
                        Image.asset(
                          "images/ic_zxyp.png",
                          height: imgHeight,
                          fit: BoxFit.fitHeight,
                        ),
                        const SizedBox(height: 3),
                        Text(
                          '甄选优品',
                          style: wrapFontStyle,
                        ),
                      ],
                    )),
                Column(
                  children: [
                    Image.asset(
                      "images/ic_qsy.png",
                      height: imgHeight,
                      fit: BoxFit.fitHeight,
                      color: Colors.white,
                    ),
                    const SizedBox(height: 3),
                    const Text(
                      '轻松游',
                      style: TextStyle(fontSize: 12, color: Colors.white),
                    ),
                  ],
                ),
                GestureDetector(
                    onTap: () {
                      Get.to(const HomeActTabPage());
                    },
                    child: Column(
                      children: [
                        Image.asset(
                          "images/ic_zxyp.png",
                          height: imgHeight,
                          fit: BoxFit.fitHeight,
                          color: Colors.white,
                        ),
                        const SizedBox(height: 3),
                        const Text(
                          '甄选优品',
                          style: TextStyle(fontSize: 12, color: Colors.white),
                        ),
                      ],
                    )),
              ],
            ),
            const SizedBox(
              height: 15,
            ),
          ],
        ),
      ),
    );
  }

  /// 热门红娘   查看更多
  Widget buildListTitle(String title, String subTitle) {
    return SliverToBoxAdapter(
        child: Container(
      margin: const EdgeInsets.fromLTRB(14, 14, 13, 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            children: [
              Container(
                width: 8,
                height: 20,
                decoration: BoxDecoration(
                    color: ThemeColor.appColor,
                    borderRadius: BorderRadius.circular(4)),
              ),
              const SizedBox(
                width: 6,
              ),
              Text(
                title,
                style: const TextStyle(
                    color: Color.fromRGBO(38, 38, 38, 1.0),
                    fontSize: 20,
                    fontWeight: FontWeight.w500),
              ),
            ],
          ),
          GestureDetector(
              onTap: () {
                if (subTitle == '查看更多') {
                  Navigator.of(context).push(MaterialPageRoute(
                      builder: (builder) => const MatcherListUi()));
                } else {
                  jumpNearByView(titleName: '附近单身驿站');
                }
              },
              child: Row(
                children: [
                  Text(
                    subTitle,
                    style: TextStyle(
                        color: ThemeColor.gray4C4C4CColor, fontSize: 14),
                  ),
                  const SizedBox(
                    width: 5,
                  ),
                  Icon(
                    Icons.arrow_forward_ios,
                    size: 14,
                    color: ThemeColor.textColorSecond,
                  ),
                ],
              ))
        ],
      ),
    ));
  }

  /// 列表
  final List _matchmakerList = [];

  Widget buildGridView() {
    double spaceMargin = 12;
    return GridView.custom(
      padding: EdgeInsets.only(
          left: spaceMargin, right: spaceMargin, bottom: spaceMargin),
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
        mainAxisSpacing: 14,
        crossAxisSpacing: 0,
        childAspectRatio: 347 / 101,
      ),
      childrenDelegate: SliverChildBuilderDelegate((context, index) {
        return buildItemView(index);
      }, childCount: _matchmakerList.length),
    );
  }

  /// 列表item
  Widget buildItemView(int index) {
    final data = _matchmakerList[index];
    double itemWidth = 62;
    bool isWoman = data['realSex'] == 2 ? true : false;
    Color textColor =
        isWoman ? ThemeColor.womanTextColor : ThemeColor.manTextColor;
    const Color black4C4E50Color = Color(0xFF4C4E50);
    final introduce = data['introduce'];
    return GestureDetector(
        onTap: () {
          if (data['memberId'].toString().isNotEmpty) {
            Navigator.of(context).push(MaterialPageRoute(
                builder: (builder) =>
                    MatcherDetailUi(data['memberId'].toString(), realSex)));
          }
        },
        child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 14),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Row(
              children: [
                SizedBox(
                  width: 62.w,
                  height: 62.w,
                  child: Stack(
                    children: [
                      Stack(
                        children: [
                          ChatNetImage(
                            imageUrl: '${data['avatarImg']}',
                            width: 62.w,
                            height: 62.w,
                            radius: 31.w,
                          ),
                          Positioned(
                            right: 5,
                            bottom: 5,
                            child: data['singleState'] == 1
                                ? Image.asset(
                              "images/ic_fdsbzh.png",
                              width: 33,
                              height: 23,
                              fit: BoxFit.fill,
                            )
                                : Container(),
                          )
                        ],
                      ),
                      Positioned(
                        right: 5,
                        bottom: 5,
                        child: data['singleState'] == 1
                            ? Image.asset(
                                "images/ic_fdsbzh.png",
                                width: 33,
                                height: 23,
                                fit: BoxFit.fill,
                              )
                            : Container(),
                      )
                    ],
                  ),
                ),
                const SizedBox(
                  width: 12,
                ),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        ConstrainedBox(
                          constraints: BoxConstraints(maxWidth: 1.sw - 150),
                          child: Text(
                            data['nickName'],
                            style: const TextStyle(
                              color: Colors.black,
                              fontSize: 14,
                            ),
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 10.w,
                    ),
                    // 地址性别
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          alignment: Alignment.center,
                          decoration: ShapeDecoration(
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(7),
                              ),
                              color: isWoman
                                  ? ThemeColor.womanColor
                                  : ThemeColor.manColor),
                          width: 40,
                          height: 14,
                          child: IconText(
                            data['age'].toString() == 'null'
                                ? '0'
                                : data['age'].toString(),
                            icon: isWoman
                                ? Image.asset(
                                    'images/user/txl_woman_icon.png',
                                    width: 12.w,
                                    height: 8.w,
                                  )
                                : Icon(Icons.male, color: textColor),
                            iconSize: 14,
                            style: TextStyle(
                              color: textColor,
                              fontSize: 10.sp,
                            ),
                          ),
                        ),
                        const SizedBox(
                          width: 5,
                        ),
                        Container(
                          decoration: BoxDecoration(
                              color: const Color(0xFFF5F5F7),
                              borderRadius: BorderRadius.circular(12)),
                          padding: const EdgeInsets.symmetric(
                              vertical: 2, horizontal: 6),
                          alignment: Alignment.center,
                          child: Text(
                            "${data['homeAddr'] ?? ""}",
                            style: const TextStyle(
                                color: black4C4E50Color,
                                fontSize: 10,
                                overflow: TextOverflow.ellipsis),
                          ),
                        )
                      ],
                    ),
                    SizedBox(
                      height: 10.w,
                    ),
                    Text(
                      introduce ?? '他很懒，什么都没写',
                      style: TextStyle(
                        fontSize: 10.sp,
                        color: introduce == null
                            ? ThemeColor.lineColor
                            : black4C4E50Color,
                      ),
                    ),
                  ],
                ),
                const Spacer(),
                Container(
                  width: 48.w,
                  height: 25.w,
                  decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(25 / 2.0),
                      border: Border.all(
                          color: '#795AFC'.stringToColor, width: 1.0)),
                  alignment: Alignment.center,
                  child: Text(
                    '看看',
                    style: TextStyle(
                        fontSize: 12.sp, color: '#795AFC'.stringToColor),
                  ),
                ),
              ],
            )));
  }

  _getList() async {
    final res = await Api.getInstance().getMatchmakerList(1000, 1);
    print('--------------$res');
    if (res['code'] == 0) {
      final data = res['data'];
      if (data != null) {
        List list = data['list'];
        if (list.isNotEmpty == true) {
          setState(() {
            _matchmakerList.addAll(list);
          });
        }
      }
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  _hasFateLine() async {
    final res = await Api.getInstance().hasFateLine();
    if (res['code'] <= 1) {
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (ctx) => const FateLineUi()));
    } else if (res['code'] == 2) {
      Navigator.of(context)
          .push(MaterialPageRoute(builder: (ctx) => const FateListUi()));
    } else {
      ThemeSnackBar.show(context, res['msg']);
    }
  }

  void jumpNearByView({String titleName = '单身驿站'}) {
    Get.to(NearByMapPage(
      pointMarkList: homeMainController.markList,
      titleStr: titleName,
      locationBack: (latitude, longitude, res) {
        homeMainController.starLon = longitude;
        homeMainController.starLat = latitude;
        homeMainController.saddress = res['address'] ?? '';
      },
    ));
  }

  void getCurrentLocation() async {
    /// [hasShow] 隐私权政策是否弹窗展示告知用户
    AMapFlutterLocation.updatePrivacyShow(true, true);

    /// [hasAgree] 隐私权政策是否已经取得用户同意
    AMapFlutterLocation.updatePrivacyAgree(true);

    /// 动态申请定位权限
    requestPermission();
    AMapFlutterLocation.setApiKey(
        MapCommonConfig.androidKey, MapCommonConfig.iosMapKey);

    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      requestAccuracyAuthorization();
    }
    _startLocation();

    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      double latitude = double.parse(result['latitude'].toString());
      double longitude = double.parse(result['longitude'].toString());
      homeMainController.getMapShopList(longitude, latitude);
    });
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
    } else {}
  }

  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
        await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
    } else {}
  }

  ///开始定位
  void _startLocation() {
    ///开始定位之前设置定位参数
    _setLocationOption();
    _locationPlugin.startLocation();
  }

  ///设置定位参数
  void _setLocationOption() {
    AMapLocationOption locationOption = AMapLocationOption();

    ///是否单次定位
    locationOption.onceLocation = true;

    ///是否需要返回逆地理信息
    locationOption.needAddress = true;

    ///逆地理信息的语言类型
    locationOption.geoLanguage = GeoLanguage.DEFAULT;

    locationOption.desiredLocationAccuracyAuthorizationMode =
        AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

    locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

    ///设置Android端连续定位的定位间隔
    locationOption.locationInterval = 2000;

    locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

    ///设置iOS端的定位最小更新距离<br>
    locationOption.distanceFilter = -1;

    locationOption.desiredAccuracy = DesiredAccuracy.HundredMeters;

    ///设置iOS端是否允许系统暂停定位
    locationOption.pausesLocationUpdatesAutomatically = false;

    ///将定位参数设置给定位插件
    _locationPlugin.setLocationOption(locationOption);
  }
}
